<!-- 笔记历史记录查看组件 -->
<template>
  <el-dialog
    v-model="dialogVisible"
    title="历史记录"
    width="80%"
    class="history-viewer"
    :before-close="handleClose"
  >
    <div class="history-container">
      <div class="history-list">
        <el-timeline>
          <el-timeline-item
            v-for="item in histories"
            :key="item.id"
            :timestamp="formatTime(item.timestamp)"
            placement="top"
            :type="selectedHistory?.id === item.id ? 'primary' : ''"
          >
            <div
              class="history-item"
              :class="{ active: selectedHistory?.id === item.id }"
              @click="selectHistory(item)"
            >
              <div class="history-title">{{ item.title }}</div>
              <div class="history-actions">
                <el-button-group>
                  <el-button
                    type="primary"
                    size="small"
                    @click.stop="restoreHistory(item)"
                  >还原</el-button>
                  <el-button
                    type="primary"
                    size="small"
                    @click.stop="compareHistory(item)"
                  >对比</el-button>
                </el-button-group>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
      <div v-if="showDiff" class="diff-view">
        <div class="diff-header">
          <div class="diff-title">文件对比</div>
          <div class="diff-info">
            <span>历史版本：{{ formatTime(selectedHistory?.timestamp) }}</span>
            <span>当前版本：{{ formatTime(Date.now()) }}</span>
          </div>
        </div>
        <div class="diff-content">
          <div class="diff-editor" ref="diffEditorRef"></div>
        </div>
      </div>
      <div v-else-if="selectedHistory" class="history-content">
        <div class="content-header">
          <div class="content-title">历史内容</div>
          <div class="content-time">{{ formatTime(selectedHistory.timestamp) }}</div>
        </div>
        <div class="content-body">
          <markdown-editor
            v-if="selectedHistory.type === 'markdown'"
            v-model="selectedHistory.content"
            :preview-mode="true"
            readonly
          />
          <rich-text-editor
            v-else
            v-model="selectedHistory.content"
            readonly
          />
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { ElMessageBox } from 'element-plus'
import * as monaco from 'monaco-editor'
import { useEditorStore } from '@/stores/editor'
import { getRelativeTime } from '@/utils/time'
import type { NoteHistory } from '@/types'
import MarkdownEditor from './MarkdownEditor.vue'
import RichTextEditor from './RichTextEditor.vue'

const props = defineProps<{
  modelValue: boolean
  noteId: string
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
}>()

const editorStore = useEditorStore()
const histories = ref<NoteHistory[]>([])
const selectedHistory = ref<NoteHistory | null>(null)
const showDiff = ref(false)
const diffEditorRef = ref<HTMLElement | null>(null)
let diffEditor: monaco.editor.IStandaloneDiffEditor | null = null

// 监听对话框显示状态
watch(() => props.modelValue, async (visible) => {
  if (visible) {
    await loadHistories()
  } else {
    selectedHistory.value = null
    showDiff.value = false
  }
})

// 加载历史记录
const loadHistories = async () => {
  try {
    histories.value = await editorStore.loadHistories(props.noteId)
  } catch (error) {
    console.error('Failed to load histories:', error)
  }
}

// 格式化时间
const formatTime = (timestamp: number) => {
  return getRelativeTime(timestamp)
}

// 选择历史记录
const selectHistory = (history: NoteHistory) => {
  selectedHistory.value = history
  showDiff.value = false
}

// 还原历史版本
const restoreHistory = async (history: NoteHistory) => {
  try {
    const result = await ElMessageBox.confirm(
      '确定要还原到这个版本吗？当前版本将被保存为新的历史记录。',
      '还原确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    if (result === 'confirm') {
      await editorStore.restoreHistory(props.noteId, history.id)
      emit('update:modelValue', false)
    }
  } catch (error) {
    // 用户取消操作
  }
}

// 比较历史版本
const compareHistory = async (history: NoteHistory) => {
  selectedHistory.value = history
  showDiff.value = true

  // 等待 DOM 更新
  await nextTick()

  // 获取当前笔记内容
  const currentNote = editorStore.activeNote

  if (!diffEditor && diffEditorRef.value && currentNote) {
    // 创建差异编辑器
    diffEditor = monaco.editor.createDiffEditor(diffEditorRef.value, {
      automaticLayout: true,
      readOnly: true,
      renderSideBySide: true,
      enableSplitViewResizing: true,
      originalEditable: false,
      modifiedEditable: false
    })

    // 设置编辑器内容
    const language = history.type === 'markdown' ? 'markdown' : 'plaintext'
    diffEditor.setModel({
      original: monaco.editor.createModel(history.content, language),
      modified: monaco.editor.createModel(currentNote.content, language)
    })
  }
}

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
}

// 组件卸载时清理
onUnmounted(() => {
  if (diffEditor) {
    diffEditor.dispose()
    diffEditor = null
  }
})
</script>

<style lang="scss" scoped>
.history-viewer {
  :deep(.el-dialog__body) {
    padding: 0;
    height: 70vh;
  }
}

.history-container {
  height: 100%;
  display: flex;
  overflow: hidden;

  .history-list {
    width: 300px;
    height: 100%;
    padding: 16px;
    border-right: 1px solid var(--el-border-color-light);
    overflow-y: auto;

    .history-item {
      padding: 8px;
      border-radius: 4px;
      cursor: pointer;

      &:hover {
        background: var(--el-fill-color-light);
      }

      &.active {
        background: var(--el-color-primary-light-9);
      }

      .history-title {
        margin-bottom: 8px;
        font-weight: bold;
      }

      .history-actions {
        display: flex;
        justify-content: flex-end;
      }
    }
  }

  .diff-view {
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .diff-header {
      flex-shrink: 0;
      padding: 16px;
      border-bottom: 1px solid var(--el-border-color-light);

      .diff-title {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 8px;
      }

      .diff-info {
        display: flex;
        justify-content: space-between;
        color: var(--el-text-color-secondary);
      }
    }

    .diff-content {
      flex: 1;
      overflow: hidden;

      .diff-editor {
        width: 100%;
        height: 100%;
      }
    }
  }

  .history-content {
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .content-header {
      flex-shrink: 0;
      padding: 16px;
      border-bottom: 1px solid var(--el-border-color-light);
      display: flex;
      justify-content: space-between;
      align-items: center;

      .content-title {
        font-size: 16px;
        font-weight: bold;
      }

      .content-time {
        color: var(--el-text-color-secondary);
      }
    }

    .content-body {
      flex: 1;
      overflow: hidden;
    }
  }
}
</style>
